package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.pojo.dto.SignInSetDetailDTO;
import com.xbongbong.paas.pojo.dto.SignInSetUpdateDTO;
import com.xbongbong.paas.pojo.vo.SignInSetVO;
import com.xbongbong.paas.service.SignInSetService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * 签到设置相关数据接口
 *
 * @author youli.chen
 * @version v1.0
 * @date 2019/1/10 9:51
 * @since v1.0
 */
@RestController
@RequestMapping(value = XbbProConstant.API_ROOT_PREFIX + "/signIn/set")
public class SignInSetController {

    @Resource
    private SignInSetService signInSetService;

    /**
     * 获取签到设置
     */
    @RequestMapping(value = "/getConfig", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getConfig(@RequestBody @Valid SignInSetDetailDTO signInSetDetailDTO, BindingResult br) {
        XbbResponse<SignInSetVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                response = this.signInSetService.getSignInSet(signInSetDetailDTO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 更新签到设置
     */
    @RequestMapping(value = "/saveConfig", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String saveConfig(@RequestBody @Valid SignInSetUpdateDTO signInSetUpdateDTO, BindingResult br) {
        XbbResponse<SignInSetVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                response = this.signInSetService.updateSignInSet(signInSetUpdateDTO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
}
